package com.fly.graphql_demo

import graphql.ExecutionInput
import graphql.GraphQL
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@SpringBootApplication
class GraphQlDemoApplication

fun main(args: Array<String>) {
    runApplication<GraphQlDemoApplication>(*args)
}

data class GraphqlRequest(
    var query: String? = null,
    var variables: Map<String, Any>? = null
)

@RestController
@RequestMapping("/fly")
class GraphqlController {

    @Autowired
    private lateinit var graphQL: GraphQL

    @PostMapping
    fun execute(@RequestBody request: GraphqlRequest): Any =
        graphQL.execute( ExecutionInput.newExecutionInput()
            .query(request.query)
            .variables(request.variables)
            .build())
            .run {
                errors.takeIf { it.isNotEmpty() }
                    ?.run { mapOf("errors" to this) }
                    ?: getData()
            }
}

